export type Methods = 'get' | 'GET' | 'post' | 'POST'

export interface AxiosRequestConfig {
    url?: string;
    method?: Methods;
    params?: Record<string, any>
    headers?: Record<string, any>
    data?: Record<string, any>,
    timeout?: number,
    transformRequest?: (data: Record<string, any>, headers: any) => any
    transformResponse?: (data: any) => any
    cancelToken?: any
    isCancel?: any
}

interface onFulfilled<V> {
    (value: V): V | Promise<V>
}
interface OnRejected {
    (error: any): any
}
export interface Interceptor<V> {
    onFulfilled?: onFulfilled<V>
    onRejected?: OnRejected
}

export class InterceptorManager<V> {
    public interceptors: Array<Interceptor<V> | null> = []
    use(onFulfilled?: onFulfilled<V>, onRejected?: OnRejected): number {
        this.interceptors.push({
            onFulfilled,
            onRejected
        })
        return this.interceptors.length - 1
    }
    eject(id: number) {
        if(this.interceptors[id]) {
            this.interceptors[id] = null
        }
    }
}

// axios.prototype.request这个方法
// promise里的t代表promise变成成功态之后resolve的值。resolve(value)
// interface约束函数的写法
export interface AxiosInstance {
    <T=any>(config:AxiosRequestConfig): Promise<AxiosResponse<T>>
    interceptors: {
        request: InterceptorManager<AxiosRequestConfig>
        response: InterceptorManager<AxiosResponse>
    }
    CancelToken?: any
    isCancel?: any
}

// Record<string, any> 相当于
/**
 * // 任意属性，属性值任意
 * interface PlainObject {
 *  [name: string]: any
 * }
 */

// t代表响应体的类型
export interface AxiosResponse<T = any> {
    data: T,
    status: number,
    statusText?: string,
    headers?: Record<string, any>,
    config?: AxiosRequestConfig
    request?: XMLHttpRequest
}